<?php


namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use fast\Random;
use app\common\library\Token;

class Sdk extends Api
{
    protected $noNeedLogin = ['*'];
    protected $_token = '';
    //今日凌晨时间戳
    protected $today = '';
    //明日凌晨时间戳
    protected $tomorrow = '';
    //当天时间范围
    protected $range = '';
    //Token有效时长
    protected $keepTime = '';

    public function _initialize()
    {
        $this->today = strtotime(date('Y-m-d')) - 1;
        $this->tomorrow = strtotime(date('Y-m-d',strtotime('+1 day')));
        $this->range = $this->today . ',' . $this->tomorrow;
        $this->keepTime = $this->tomorrow - time();
    }



    /**
     * 入口
     *
     * @param string $appName  app名称
     * @param int $appId   appId
     * @param string $consumer app用户的唯一标
     * @param string $ip 用户的ip
     * @param string $type 进入类型：1app进入，2sdk进入
     */
    public function entry()
    {
        $this->checkParam('appName,appId,consumer,ip,type');
        $appName= $this->request->request('appName');
        $appId= $this->request->request('appId');
        $consumer= $this->request->request('consumer');
        $ip= $this->request->request('ip');
        $type= $this->request->request('type');

        $app = Db::table('sdk_app')->where('id', $appId)->where('name', $appName)->where('status', 0)->find();
        if (!$app) {
            $this->error(__('参数有误,请检查'));
        }

        $appUser = Db::table('sdk_app_user')->where('app_id', $appId)->where('consumer', $consumer)->find();
        if (!$appUser) {
            $appUserId = Db::table('sdk_app_user')->insertGetId([
                'app_id' => $appId,
                'consumer' => $consumer,
                'createtime' => time(),
                'joinip' => $ip]);
        } else {
            $appUserId = $appUser['id'];
        }
        /*$today = strtotime(date('Y-m-d'));
        $tomorrow = strtotime(date('Y-m-d',strtotime('+1 day')));
        $range = $today . ',' . $tomorrow;*/

        $loginRecord = Db::table('sdk_login_record')->where('time','between', $this->range)->where('app_user_id', $appUserId)->find();
        if (!$loginRecord) {
             Db::table('sdk_login_record')->insertGetId([
                'app_user_id' => $appUserId,
                'time' => time(),
                'ip' => $ip,
                'type' => $type]);
        }
        $account = Db::table('sdk_account')->where('app_user_id', $appUserId)->column('coin,dollar,card');
        if (empty($account)) {
            Db::table('sdk_account')->insert(['app_user_id' => $appUserId,
                'coin' => 0,
                'dollar' => 0,
                'card' => 0]);
        }

        $this->_token = Random::uuid();
        Token::clear($appUserId);
        Token::set($this->_token, $appUserId, $this->keepTime);
        $this->success(__('成功'), ['token' => $this->_token, 'account' => Db::table('sdk_account')->where('app_user_id', $appUserId)->column('coin,dollar,card')]);
    }

    /**
     * 签到
     *
     * @param string $token  token
     * @param string $ip 用户的ip
     * @param string $type 签到类型：1普通签到，2广告签到
     */
    public function sign()
    {
        $this->checkParam(['ip','type']);
        $this->checkParam('token', 'head');
        $token = $this->request->header('token');
        $type = $this->request->request('type');
        $ip = $this->request->request('ip');
        $appUserId = Token::get($token);
        if (!$token || !$appUserId) {
            $this->error(__('Token不存在'));
        }
        $signRecord = Db::table('sdk_sign')->where('time','between', $this->range)->where('app_user_id', $appUserId)->find();
        if ($signRecord) {
            $this->error(__('您已签到'));
        }
        $res = Db::table('sdk_sign')->insertGetId([
            'app_user_id' => $appUserId,
            'time' => time(),
            'ip' => $ip,
            'type' => $type]);
        if ($res) {
            $this->success(__('签到成功'));
        } else {
            $this->error(__('服务器错误请稍后再试'));
        }
    }

    /**
     * 广告记录
     *
     * @param string $token  token
     * @param string $ip 用户的ip
     * @param string $type 签到类型：1普通签到，2广告签到
     */
    public function advertisingRecord()
    {

    }

    /**
     * 转盘记录
     *
     * @param string $token  token
     * @param string $type 玩法的类型：0消耗，1金币消耗获得一次，2看广告获得三次,3每天三次免费
     */
    public function spinRecord()
    {
        $this->checkParam(['type']);
        $this->checkParam('token', 'head');
        $token = $this->request->header('token');
        $type = $this->request->request('type');
        $appUserId = Token::get($token);
        if (!$token || !$appUserId) {
            $this->error(__('Token不存在'));
        }

        //判断是否添加过每日刷新三次转盘机会
        $everyday = Db::table('sdk_spin_record')->where('app_user_id', $appUserId)->where('time', '>',$this->today)->where('type',3)->find();
        if (!$everyday) {
             Db::table('sdk_spin_record')->insertGetId([
                'app_user_id' => $appUserId,
                'time' => time(),
                'count' => 3,
                'type' => 3]);
        }
        $reduce = Db::table('sdk_spin_record')->where('app_user_id', $appUserId)->where('type', 0)->sum('count');
        $add = Db::table('sdk_spin_record')->where('app_user_id', $appUserId)->where('type', 1)->whereOr('type',2)->sum('count');
        $everyday = Db::table('sdk_spin_record')->where('id', $everyday['id'])->column('count');
        $free  = $add - $reduce + $everyday;
        if ($free < 1) {
            $this->error(__('已经没有转盘机会'));
        }
        //判断转盘记录每天免费三次机会是否用完，没用完则首先消耗免费的三次机会
        if ($type == 0) {
            if ($everyday['count'] != 0) {
                Db::table('sdk_spin_record')->where('id', $everyday['id'])->update(['count' => $everyday['count'] - 1]);
            } else {
                Db::table('sdk_spin_record')->insert([
                    'app_user_id' => $appUserId,
                    'time' => time(),
                    'count' => 1,
                    'type' => 0]);
            }

        } elseif ($type == 1) {
            $coin = Db::table('sdk_account')->where('app_user_id', $appUserId)->column('coin');
            if ($coin - 4000 >= 0) {
                Db::table('sdk_account_record')->insert(['app_user_id' => $appUserId,
                    'coin' => 4000,
                    'type' => 2,
                    'flow' => 'spin',
                    'time' => time()]);
                Db::table('sdk_account')->where('app_user_id', $appUserId)->update(['coin' => $coin - 4000]);
                Db::table('sdk_spin_record')->insertGetId([
                    'app_user_id' => $appUserId,
                    'time' => time(),
                    'count' => 1,
                    'type' => 1]);
            } else {
                $this->error(__('账户金币不足'));
            }
        } elseif ($type == 2) {
            Db::table('sdk_spin_record')->insertGetId([
                'app_user_id' => $appUserId,
                'time' => time(),
                'count' => 3,
                'type' => 2]);
        }

        $this->success(__('成功'), ['free' => $free - 1]);
    }

    /**
     * 用户行为
     *
     * @param string $token  token
     * @param string $event 事件
     * @param param $param 参数
     */
    public function action()
    {
        $this->checkParam(['ip','event','param']);
        $this->checkParam('token', 'head');
        $token = $this->request->header('token');
        $event = $this->request->request('event');
        $param = $this->request->request('param');
        $appUserId = Token::get($token);
        if (!$token || !$appUserId) {
            $this->error(__('Token不存在'));
        }
        $res = Db::table('sdk_action')->insertGetId([
            'app_user_id' => $appUserId,
            'time' => time(),
            'event' => $event,
            'param' => json_encode($param)]);
        if ($res) {
            $this->success(__('成功'));
        } else {
            $this->error(__('服务器错误请稍后再试'));
        }
    }

    /**
     * 用户奖励
     *
     * @param string $token  token
     * @param string $ip 用户的ip
     * @param string $type 签到类型：1普通签到，2广告签到
     */
    public function award()
    {

    }

    /**
     * 用户任务
     *
     * @param string $token  token
     * @param string $ip 用户的ip
     * @param string $type 签到类型：1普通签到，2广告签到
     */
    public function task()
    {

    }

    public function cashOut()
    {

    }
}